-module(test).
-export([test_if/2]).
-export([month_length/2]).

% map test
-export([convert_list_to_c/1]).
-export([test_map/0]).

% foreach test
-export([test_foreach/0]).

% sort test
-export([test_sort/0]).

% spawn test
-export([test_spawn/0, say_something/2]).

% ping pong test
-export([test_ping_pong/0, ping/2, pong/0]).

ping(0, Pong_PID)->
	Pong_PID ! finished,
	io:format("ping finished~n", []);
ping(N, Pong_PID)->
	Pong_PID ! {ping, self()},
	receive
		pong->
			io:format("Ping receive pong~n", [])
	end,
	ping(N-1, Pong_PID).
pong()->
	receive
		finished->
			io:format("Pong finished~n", []);
		{ping, Ping_PID}->
			io:format("Pong receive ping~n", []),
			Ping_PID ! pong,
			pong()
	end.
test_ping_pong()->
	Pong_PID = spawn(test, pong, []),
	spawn(test, ping, [3, Pong_PID]).

say_something(_,0)->
	done;
say_something(What, Times)->
	io:format("~p~n",[What]),
	say_something(What, Times-1).
test_spawn()->
	spawn(test, say_something, [hello, 3]),
	spawn(test, say_something, [goodbye, 3]).

test_sort()->
	New_list = test_map(),
	lists:sort(fun({_, {c, Temp1}}, {_, {c, Temp2}})-> Temp1 < Temp2 end, New_list).


print_city({City, {X, Temp}})->
	io:format("~-15w ~w ~w ~n", [City, X, Temp]).

test_foreach()->
	lists:foreach(fun print_city/1, [{moscow, {c, -10}}, {cape_town, {f, 70}}, {stockholm, {c, -4}}, {paris, {f, 28}}, {london, {f, 36}}]).

convert_to_c({Name, {f, Temp}})->
	{Name,{c, trunc((Temp-32)*5/9)}};
convert_to_c({Name, {c, Temp}})->
	{Name,{c, Temp}}.
convert_list_to_c(List)->
	lists:map(fun convert_to_c/1, List).

test_map()->
	convert_list_to_c([{moscow, {c, -10}}, {cape_town, {f, 70}}, {stockholm, {c, -4}}, {paris, {f, 28}}, {london, {f, 36}}]).


month_length(Year, Month)->
	Leap = if
		       trunc(Year/400)*400 == Year ->
			       leap;
		       trunc(Year/100)*100 == Year ->
			       not_leap;
		       trunc(Year/4)*4 == Year ->
			       leap;
		       true->
			       not_leap
	       end,
	case Month of
		jan->31;
		feb when Leap == leap ->29;
		feb->28;
		mar->31;
		apr->30;
		may->31;
		jun->30;
		jul->31;
		aug->31;
		sep->30;
		oct->31;
		nov->30;
		dec->31
	end.

test_if(A, B)->
	if
		A==5 ->
			io:format("A = 5~n", []),
			a_equals_5;
		B==6 ->
			io:format("B = 6~n", []),
			b_equals_6;
		A==2,B==3 ->	%ie.e, A equals 2 and B equals 3
			io:format("A=2, B=3~n", []),
			a_equals_2_b_equals_3;
		A==1;B==7 ->
			io:format("A=1; B=7~n", []),
			a_equals_1_or_b_equals_7
	end.

